package com.blog.controller;


import com.blog.common.Result.PageResult;
import com.blog.common.Result.Result;
import com.blog.common.constant.JwtClaimsConstant;
import com.blog.dto.UserDto;
import com.blog.dto.UserRegisterDto;
import com.blog.entity.User;
import com.blog.properties.JwtProperties;
import com.blog.service.IUserService;
import com.blog.utils.JwtUtil;
import com.blog.vo.UserGetInfoVo;
import com.blog.vo.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
@Slf4j
@RequiredArgsConstructor
public class UserController {


    private final IUserService userService;

    private final JwtProperties jwtProperties;


    /**
     * 用户登录
     * @param userDto
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public Result<UserLoginVo> login(@RequestBody UserDto userDto){
        log.info("用户:{}",userDto);
        User user = userService.login(userDto);

        //进行登录成功后，生成jwt令牌，并返回给前端
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ID, user.getId());
        //生成令牌
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims
        );
        UserLoginVo userLoginVo = new UserLoginVo();
        BeanUtils.copyProperties(user,userLoginVo);
        userLoginVo.setToken(token);
        return Result.success(userLoginVo);
    }


    /**
     * 用户注册
     * @param userRegisterDto
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public Result<String> register(@RequestBody UserRegisterDto userRegisterDto){
        log.info("用户注册:{}",userRegisterDto);
        userService.register(userRegisterDto);
        return Result.success("注册成功");
    }

    /**
     * 用户退出登录
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("用户退出登录接口")
    public Result<String> logout(){
        log.info("用户退出登录");
        return Result.success("退出成功");
    }


    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getUsers")
    @ApiOperation("获取用户列表")
    public Result<PageResult> getPageUsers(Integer pageNum, Integer pageSize){
        log.info("分页获取用户列表：{} {}",pageNum,pageSize);
        PageResult pageResult = userService.getUsers(pageNum,pageSize);
        return Result.success(pageResult);
    }

}
